package com.hands.netty.service.impl;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.hands.commen.entity.netty.Us;
import com.hands.commen.entity.wx.MsgEntity;
import com.hands.commen.entity.wx.MsgHeader;
import com.hands.service.WxxRpcService;

import com.hands.netty.netty.NioServerHandler;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.rpc.AsyncContext;
import org.apache.dubbo.rpc.RpcContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//boot
//@Service
@Service(interfaceClass = WxxRpcService.class, version = "1.0.1", timeout = 15000)
public class WxRpcServiceImpl implements WxxRpcService {


	private static final Logger logger = LoggerFactory.getLogger(WxRpcServiceImpl.class);


	//public  static Map<String,AsyncContext > asyncContextMap = new HashMap<String, AsyncContext>();


	public static Cache<String, AsyncContext> asyncContextMap = CacheBuilder.newBuilder()
			.expireAfterWrite(1L, TimeUnit.MINUTES)  //写入1分钟后过期
			.maximumSize(50000L)
			.build();


	@Resource
	private NioServerHandler nioServerHandler;
	



	@Override
	public String test(String msg) {

		System.out.println("查询商品：");
		return "连接测试";
	}

	/**
	 * 微信小程序下发指令
	 * @param msg
	 * @return
	 */
	@Override
	public String InstructionsInfo(MsgEntity msgEntity) throws InterruptedException {

		logger.info("传过来的原始数据{}",msgEntity);
		MsgHeader header = msgEntity.getHeader();
		String toUserId = header.getToUserId();
		Us us = NioServerHandler.mapString.get(toUserId);
		String resMsg="";
		final AsyncContext asyncContext = RpcContext.startAsync();
		if(us !=null){
			//消息发送
			String msg = JSON.toJSONString(msgEntity);
			nioServerHandler.setCleitMsgByString(us.ctx,msg);
			asyncContextMap.put(header.getMsgId(),asyncContext);
			//异步信息返回
			//asyncInfo(header,asyncContext);
		}else{
			//主机不在线
			header.setRespCode(10000);
			header.setRespMsg("主机不在线稍后再试");
			HashMap<String, Object> map = new HashMap<>();
			map.put("header", header);
			String smg=JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
			asyncContext.write(smg);
		}
		return null;

	}

	//异步消息返回
	private void asyncInfo(MsgHeader header,AsyncContext asyncContext) {
		final JSONObject ifPresent = NioServerHandler.cache.getIfPresent(header.getMsgId());
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				//asyncContext.signalContextSwitch();
				//获取缓存数据
				//JSONObject ifPresent = NioServerHandler.cache.getIfPresent(header.getMsgId());
				JSONObject ifMsg=ifPresent;
				while (true){
					if(ifMsg == null || ifMsg.isEmpty() || "null".equals(ifMsg)){
						ifMsg= NioServerHandler.cache.getIfPresent(header.getMsgId());
					}else{
						NioServerHandler.cache.invalidate(header.getMsgId());
						asyncContext.write(ifMsg.toString());
						break;
					}

				}
			}
		});
		t.start();
	}
}
